const host = 'http://localhost:8000'

// 服务器使用：
// const host = 'http://{域名或ip}:8000'

function sel() {
    $('.booklist > tr').remove()
    init()
}

function add() {
    location.href = './bookAddOrEdit.html'

}

function edit(id) {
    location.href = `./bookAddOrEdit.html?id=${id}`

}

function del(id) {
    if (confirm('确定要删除吗')) {
        axios.delete(`${host}/books/${id}`).then(res => {
            if (res.data.code === 1000) {
                alert('删除成功')
                location.href = './book.html'
            }
        })
    }
}

//原js
// window.addEventListener('load', function () {
// axios.get(`${host}/books`).then(res => {
//         const data = res.data.data
//         const booklist = document.querySelector('.booklist')
//         booklist.innerHTML += data.map(item =>
//             `
//                 <tr>
//                     <td>${item.id}</td>
//                     <td>${item.bookName}</td>
//                     <td>${item.author}</td>
//                     <td>${item.descriptions}</td>
//                     <td>
//                         <input type="button" value="编辑" onclick="edit(${item.id})">
//                         <input type="button" value="删除" onclick="del(${item.id})">
//                     </td>
//                 </tr>
//             `
//         ).join('')
//     })
// })

//jQuery
const init = function () {
    const keyword = $('input[name=keyword]').val().trim()
    axios.get(`${host}/books?keyword=${keyword}`).then(res => {
        const data = res.data.data
        const html = data.map(item =>
            `
                <tr>
                    <td>${item.id}</td>
                    <td>${item.bookName}</td>
                    <td>${item.author}</td>
                    <td>${item.descriptions}</td>
                    <td>
                        <input type="button" value="编辑" onclick="edit(${item.id})">
                        <input type="button" value="删除" onclick="del(${item.id})">
                    </td>
                </tr>
            `
        ).join('')
        $('.booklist').append(html)
    })
}
init()